package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	"google.golang.org/grpc"

	pb "gitee.com/aoliang/graceful/quick_close_grpc/proto"
)

const (
	address2 = "localhost:50051"
)

func main() {
	conn, err := grpc.Dial(address2, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	c := pb.NewGreeterClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	streamClient, err := c.SayStreamHello(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	waitc := make(chan struct{})
	go func() {
		for {
			in, err := streamClient.Recv()
			if err == io.EOF {
				// read done.
				close(waitc)
				return
			}
			if err != nil {
				fmt.Printf("Failed to receive a message : %v", err)
				return
			}
			log.Printf("Got message %s", in.Message)
		}
	}()

	var i int
	for {
		if err := streamClient.Send(&pb.HelloRequest{Name: fmt.Sprintf("message-%d", i)}); err != nil {
			fmt.Printf("Failed to send a note: %v", err)
			return
		}
		i++
		time.Sleep(time.Duration(10) * time.Millisecond)
	}

}
